package org.example.apiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.example.apiclientsdk.model.User;

import java.util.HashMap;
import java.util.Map;

import static org.example.apiclientsdk.utils.SignUtils.getSign;

/**
 * 调用第三方接口的客户端
 * @version 1.0
 * @Description:
 * @date 2022/4/1
 */
public class ApiClient {

    private static final String GATEWAY_HOST = "http://localhost:8090";

    private String accessKey;
    private String secretKey;

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name){
        HashMap<String,Object> map = new HashMap<>();
        map.put("name",name);
        String result = HttpUtil.get(GATEWAY_HOST+"/api/name/",map);
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name){
        HashMap<String,Object> map = new HashMap<>();
        map.put("name",name);
        String result = HttpUtil.post(GATEWAY_HOST+"/api/name/",map);
        System.out.println(result);
        return result;
    }

    private Map<String,String> getHeadersMap(String body){
        Map<String,String> hashMapmap = new HashMap<>();
        hashMapmap.put("accessKey",accessKey);
        //secretKey一定不能给后端
        //hashMapmap.put("secretKey",secretKey);
        hashMapmap.put("nonce", RandomUtil.randomNumbers(4));
        hashMapmap.put("body",body);
        hashMapmap.put("timestamp",String.valueOf(System.currentTimeMillis()/1000));
        hashMapmap.put("sign",getSign(body,secretKey));
        return hashMapmap;
    }
    public String getUserNameByPost(User user){
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST+"/api/name/user")
                .charset("UTF-8")
                .addHeaders(getHeadersMap(json))
                .body(json).execute();
        System.out.println(httpResponse.getStatus());
        System.out.println(httpResponse.body());
        return httpResponse.body();
    }
}
